package com.zc.basic.infra.mybatis.type;

import com.zc.basic.domain.pojo.gis.GeoPoint;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.stereotype.Component;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Component
public class PointTypeHandler extends BaseTypeHandler<GeoPoint> {

    private static final String GEOM_FROM_TEXT = "GeomFromText";
    private static final String BRACKETS_L = "(";
    private static final String BRACKETS_R = ")";
    private static final String POINT = "POINT";
    private static final String SPACE = " ";
    private static final String COMMA = "'";

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, GeoPoint geoPoint, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, getGeomPointText(geoPoint));
    }

    @Override
    public GeoPoint getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return new GeoPoint();
    }

    @Override
    public GeoPoint getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return new GeoPoint();
    }

    @Override
    public GeoPoint getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return new GeoPoint();
    }

    private String getGeomPointText(GeoPoint geoPoint) {

        return GEOM_FROM_TEXT + SPACE + BRACKETS_L +
                SPACE + COMMA + POINT + BRACKETS_L
                + geoPoint.getLongitude().toPlainString() + SPACE + geoPoint.getLatitude().toPlainString() + BRACKETS_R
                + COMMA + SPACE + BRACKETS_R + SPACE + BRACKETS_R;

    }

}
